package com.moarea.app.filter;

import com.moarea.app.lang.utils.StringUtils;
import com.moarea.app.util.PropertyUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Properties;

/**
 * 登录控制过滤器
 */
public class LoginFilter implements Filter {

    //链接数组
    private String[] noFilterUrls = null;
    //处理properties文件的工具类
    public Properties property = null;

    //过滤器销毁执行
    public void destroy() {
        this.noFilterUrls = null;
        this.property = null;
    }

    //过滤器入口
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String uri = httpServletRequest.getRequestURI();//获取传入的url
        String contextPath = httpServletRequest.getContextPath();//获取Uri(http://localhost:8080/RIGOL_PM)
        uri = uri.substring(contextPath.length());//获取除去(http://localhost:8080/RIGOL_PM)这个之后的所有链接内容
        boolean isNoFilter = validatorUrls(uri);//验证是否是被排除的不需要过滤的链接,如果是的话，则需要直接放行

        //取出存储在session中的数据，判断用户是否已经登录
        String GUID = (String) httpServletRequest.getSession().getAttribute("GUID");
        boolean isLogin = StringUtils.isNotBlank(GUID);

        if (isNoFilter || isLogin) {
            //如果已经登录，或者不需要过滤，则直接放行
            filterChain.doFilter(request, response);
        } else {
            //否则，没有登录的情况下，先判断，这个请求是否是请求controller层请求
            //如果是的话，则表明用户已经登录，只是已经过期了，则提示登录已失效
            int flag = uri.indexOf("/api/");
            if (flag >= 0) {
                //可以做额外的一些处理，但这里这暂时直接跳转到登录页面
                httpServletResponse.sendRedirect(((HttpServletRequest) request).getContextPath().concat("/index.html"));
            } else {
                //否则，用户是首次登录
                //跳转到登录界面
                httpServletResponse.sendRedirect(((HttpServletRequest) request).getContextPath().concat("/index.html"));
            }
        }
    }

    //过滤器初始化
    public void init(FilterConfig config) throws ServletException {
        String bns = config.getInitParameter("noFilterUrls");
        this.noFilterUrls = bns.split(",");
        this.property = PropertyUtil.getReportConfig();
    }

    //验证url
    private boolean validatorUrls(String uri) {
        String url = replace(uri);//url连接格式处理
        boolean flag = false;
        for (int i = 0; i < noFilterUrls.length; i++) {
            if (url.indexOf(noFilterUrls[i]) == 0) {//如果没有匹配的链接，则返回false
                flag = true;
                break;
            }
        }
        return flag;
    }

    //---遇到//换成/，这样可以准确匹配
    private String replace(String uri) {
        String url = uri;
        while (url.contains("//")) {
            url = url.replace("//", "/");
        }
        return url;
    }
}
